import router from './router'
import NProgress from 'nprogress'
import { Route } from 'vue-router'
import micro from '@/micro'

NProgress.configure({ showSpinner: false })

// 全局设置title
const getPageTitle = (key: string) => {
  return key
}

router.beforeEach((to: Route, from: Route, next: any) => {
  if (to.matched && to.matched.length > 0) {
    next()
  } else {
    const base =
      process.env.BASE_URL && process.env.BASE_URL.replace(/^\/|\/$/g, '')
    const reg = new RegExp('^\\/' + base + '\\/')
    if (reg.test(location.pathname)) {
      next('/404')
    } else {
      next()
    }
  }
})
router.afterEach((to: Route) => {
  // 如果子应用有meta信息，则改变主应用的meta信息，这样方便子应用独立管理detail这种没有在菜单中的页面
  if (to.meta) {
    micro.setGlobalState({ meta: to.meta })
  }
  // Finish progress bar
  NProgress.done()
  // set page title
  document.title = getPageTitle(to.meta.title ? `星云管理后台` : '...')
})
